package com.r2coding.domain.strategy.service.rule.impl.before;

import com.r2coding.domain.strategy.model.entity.RuleActionEntity;
import com.r2coding.domain.strategy.model.entity.RuleMatterEntity;
import com.r2coding.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import com.r2coding.domain.strategy.repository.IStrategyRepository;
import com.r2coding.domain.strategy.service.annotation.LogicStrategy;
import com.r2coding.domain.strategy.service.rule.IRuleLogicFilter;
import com.r2coding.domain.strategy.service.rule.factory.DefaultLogicFactory;
import com.r2coding.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author caolx
 * @description 用户权重抽奖规则过滤 实现类
 * @date 2025/8/2 14:57
 */
@Slf4j
@Service
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_WEIGHT)
@SuppressWarnings("all")
public class RuleWeightLogicFilter implements IRuleLogicFilter<RuleActionEntity.RaffleBeforeEntity> {

    @Resource
    private IStrategyRepository strategyRepository;

    public Long userScore = 4500L;

    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
        log.info("规则过滤-权重范围 userId: {}, strategyId: {}", ruleMatterEntity.getUserId(), ruleMatterEntity.getStrategyId());

        // 暂时写死用户积分值为userScore
        String userId = ruleMatterEntity.getUserId();
        Long strategyId = ruleMatterEntity.getStrategyId();
        // 4000:102,103,104,105;5000:102,103,104,105,106,107;6000:102,103,104,105,106,107,108,109
        String ruleValue = strategyRepository.queryStrategyRuleValue(strategyId, ruleMatterEntity.getAwardId(), ruleMatterEntity.getRuleModel());

        List<Integer> configRuleWeightList = getRuleWeightConfigList(ruleValue);
        // 找到用户已解锁的最高权重范围
        Integer matchConfigWeight = configRuleWeightList.stream()
                .filter(key -> userScore >= key)
                .max(Long::compare)
                .orElse(null);

        if (matchConfigWeight != null) {
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .ruleModel(ruleMatterEntity.getRuleModel())
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .strategyId(strategyId)
                            .ruleWeightValue(matchConfigWeight)
                            .build())
                    .build();
        }

        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }

    /**
     * 解析4000:102,103,104,105;5000:102,103,104,105,106,107;6000:102,103,104,105,106,107,108,109 得到配置的权重列表
     *
     * @param ruleValue 权重范围配置
     * @return 设定的权重范围列表
     */
    private List<Integer> getRuleWeightConfigList(String ruleValue) {
        String[] ruleValueGroup = ruleValue.split(Constants.COMMA);
        List<Integer> ruleWeightList = new ArrayList<>();
        for (String weightRuleValue : ruleValueGroup) {

            // 分割字符串获取键值
            String[] parts = weightRuleValue.split(Constants.COLON);
            if (parts.length != 2) {
                throw new IllegalArgumentException("rule_weight rule_value invalid input format: " + weightRuleValue);
            }
            ruleWeightList.add(Integer.parseInt(parts[0]));
        }
        return ruleWeightList;
    }
}
